import React from 'react'
import './index.scss'
import NavHeader from '../../components/NavHeader'
import { getPostionCity } from '../../utils/getCity'
import { getAreaHouse } from '../../api/area'
import HouseList from './components/HouseList'
import { getHouseList } from '../../api/house'
import styles from './index.module.css'
const BMap = window.BMap

//设置地图覆盖物默认样式
const LABEL_STYLE = {
  cursor: 'pointer',
  border: '0px solid rgb(255, 0, 0)',
  padding: '0px',
  whiteSpace: 'nowrap',
  fontSize: '12px',
  color: 'rgb(255, 255, 255)',
  textAlign: 'center',
}
export default class Map extends React.Component {
  state = {
    isSHowList: false,
    houseList: [],
  }

  async componentDidMount() {
    this.initMap()
  }

  // 初始化地图
  async initMap() {
    const { label, value } = await getPostionCity()
    //创建地址解析器实例
    const myGeo = new BMap.Geocoder()
    myGeo.getPoint(
      label,
      async (point) => {
        if (point) {
          // 创建一个地图实例
          this.map = new BMap.Map('container')
          const map = this.map
          map.addEventListener('movestart', () => {
            // console.log(123)
            if (this.state.isSHowList) {
              console.log(123)
              this.setState({
                isSHowList: false,
              })
            }
          })
          // 初始化地图
          map.centerAndZoom(point, 11)
          const scaleCtrl = new BMap.ScaleControl() // 添加比例尺控件
          map.addControl(scaleCtrl)
          const navigation = new BMap.NavigationControl() // 添加缩放控件
          map.addControl(navigation)
          this.renderOverlays(value)
        }
      },
      label
    )
  }
  // 渲染覆盖物入口
  async renderOverlays(id) {
    // 发送请求获取房源信息
    const { data: res } = await getAreaHouse(id)
    const { nextZoom, type } = this.getTypeAndZoom()
    res.body.forEach((item) => {
      this.createOverlays(nextZoom, type, item)
    })
  }
  // 创建覆盖物
  createOverlays(nextZoom, type, data) {
    if (type === 'circle') return this.createCircle(data, nextZoom)
    this.createRect(data)
  }
  // 创建区和镇的房源覆盖物
  createCircle(data, zoom) {
    const {
      coord: { latitude, longitude },
      value,
      label,
      count,
    } = data
    const labelPoint = new BMap.Point(longitude, latitude)
    // 添加文本覆盖物
    const opts = {
      position: labelPoint,
      offset: new BMap.Size(-35, -35),
    }
    const BMAP_LABEL = new BMap.Label(null, opts)
    // 设置地图覆盖物默认样式
    BMAP_LABEL.setStyle(LABEL_STYLE)
    // 添加覆盖物
    this.map.addOverlay(BMAP_LABEL)

    // 给覆盖物注册单击事件
    BMAP_LABEL.addEventListener('click', () => {
      this.map.centerAndZoom(labelPoint, zoom)
      this.renderOverlays(value)
      setTimeout(() => {
        this.map.clearOverlays()
      })
    })

    // 自定义覆盖物的结构
    BMAP_LABEL.setContent(`
            <div class="${styles.bubble}">
            <p class="${styles.name}">${label}</p>
            <p>${count}套</p>
            </div>
          `)
  }
  // 创建小区的覆盖物
  createRect = (data) => {
    const {
      coord: { latitude, longitude },
      value,
      label,
      count,
    } = data
    const labelPoint = new BMap.Point(longitude, latitude)
    // 添加文本覆盖物
    const opts = {
      position: labelPoint,
      offset: new BMap.Size(-50, -10),
    }
    const BMAP_LABEL = new BMap.Label(null, opts)
    BMAP_LABEL.setContent(`
    <div class="${styles.rect}">
      <span class="${styles.housename}">${label}</span>
      <span class="${styles.housenum}">${count}套</span>
      <i class="${styles.arrow}"></i>
    </div>
    `)
    BMAP_LABEL.setStyle({
      cursor: 'pointer',
      border: '0px solid rgb(255, 0, 0)',
      padding: '0px',
      whiteSpace: 'nowrap',
      fontSize: '12px',
      color: 'rgb(255, 255, 255)',
      textAlign: 'center',
    })
    // 给覆盖物注册单击事件
    BMAP_LABEL.addEventListener('click', (e) => {
      const mapX = window.innerWidth / 2
      const mapY = (window.innerHeight - 330) / 2
      const labelPosition = e.target.ca.getBoundingClientRect()

      this.map.panBy(mapX - labelPosition.x - 50, mapY - labelPosition.y - 10)
      this.loadHouseList(value)
    })
    this.map.addOverlay(BMAP_LABEL)
  }
  // 点击小区获取房源信息
  async loadHouseList(value) {
    const { data: res } = await getHouseList(value)
    this.setState({
      isSHowList: true,
      houseList: res.body.list,
    })
  }
  //获取地图渲染类型和层级
  getTypeAndZoom() {
    const zoom = this.map.getZoom()
    let nextZoom = 11
    let type = 'circle'
    if (zoom === 11) {
      nextZoom = 13
    } else if (zoom === 13) {
      nextZoom = 16
    } else {
      type = 'rect'
    }
    return {
      nextZoom,
      type,
    }
  }
  render() {
    const { isSHowList, houseList } = this.state
    return (
      <div className="map">
        <NavHeader>地图找房</NavHeader>
        <div id="container"></div>
        <HouseList houseList={houseList} isSHowList={isSHowList}></HouseList>
      </div>
    )
  }
}
